package com.example.crossmall.service.impl;

import com.example.crossmall.mapper.AdminMapper;
import com.example.crossmall.po.Admin;
import com.example.crossmall.po.AdminExample;
import com.example.crossmall.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    AdminMapper adminMapper;
    @Override
    public Admin findById(int id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    @Override
    public Page<Admin> findAll(Pageable pageable) {
        return null;
    }

    @Override
    public List<Admin> findAllExample(AdminExample example) {
        return adminMapper.selectByExample(example);
    }

    @Override
    public void update(Admin adminUser) {
        adminMapper.updateByPrimaryKeySelective(adminUser);
    }

    @Override
    public int create(Admin adminUser) {
        adminMapper.insert(adminUser);
        return adminUser.getId();
    }

    @Override
    public void delById(int id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Admin checkLogin(HttpServletRequest request, String username, String pwd) {
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username)
                .andPasswordEqualTo(pwd);
        List<Admin> adminList = adminMapper.selectByExample(example);
        Admin admin = null;
        if (!adminList.isEmpty()){
            admin = adminList.get(0);
            request.getSession().setAttribute("login_user", admin);
        }
        else {
            throw new LoginException("用户名或密码错误");
        }
        return admin;
    }
}
